<?php
/**
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     function
 * Name:     pmvc_formInputCheckbox
 * Purpose:  renders form checkboxes
 * -------------------------------------------------------------
 */

use pmvc\template\smarty\SmartyUtil;

require_once(__DIR__."/function.pmvc_formInput.php");

function smarty_function_pmvc_formInputCheckbox(array $params, &$smarty) {

    $request = SmartyUtil::getRegisteredObject($smarty, "Request", true);

    // setup type
	$params["type"] = "checkbox";

	// get selected options
	$selectedOptions = SmartyUtil::getSelectedOptions($params, $smarty);
	unset($params["selectedOptions"]);

	// pre-select from selectedOptions
    if (count($selectedOptions)>0
    	&& isset($params["name"])
    	&& isset($params["value"])
    	&& array_search($params["value"], $selectedOptions)!==false) {
    	$params["checked"] = "checked";
    	
    } else if (isset($params["checked"])) {
    	if (($params["checked"] === true) || ($params["checked"] == "checked")) {
    		$params["checked"] = "checked";
    	} else {
    		unset($params["checked"]);
    	}
    }

    // avoid duplicate ids
    if (!isset($params["id"]) && isset($params["name"]) && isset($params["value"])) {
    	$params["id"] = $params["name"]."_".$params["value"];
    }

    // render it
	return smarty_function_pmvc_formInput($params, $smarty, false);
}

?>